#include "udp_socket.h"
#include <cstring>
#include <cerrno>
#include <stdio.h>


UDP_socket::UDP_socket()
{
    _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
}


void UDP_socket::write(string data)
{
    const char * buf;
    bzero(&buf, sizeof(buf)); 
    buf = data.c_str();

    struct sockaddr_in * dest;

    dest=getServ_addr();
    size_t add_len = sizeof(*dest);

    if ((sendto(_sockfd, buf, strlen(buf), 0, (struct sockaddr *) dest, add_len))==-1)
    {
        error ("sendto of write");
        printf("Error SENDTO: %s (%d)\n", strerror(errno), errno);
    }
}

void UDP_socket::read(string & data)
{
    char buf [1024];
    bzero(buf, 1024);

    int add_len = sizeof(_sender_addr);

    if ((recvfrom(_sockfd, buf, 1024, 0,(struct sockaddr *)&_sender_addr, (socklen_t*)&add_len))<0)
    {
        error("recv of read");
        printf("Error: %s (%d)\n", strerror(errno), errno);
    }

    data = string(buf);
}

void UDP_socket::setReceiverAdress()
{
    _serv_addr.sin_addr.s_addr= _sender_addr.sin_addr.s_addr;
    _serv_addr.sin_family=_sender_addr.sin_family;
    _serv_addr.sin_port=_sender_addr.sin_port;
}

void UDP_socket::bind()
{
    struct sockaddr_in *server= getServ_addr();
    size_t add_len = sizeof(*server);

    if ((::bind(getSockfd(), (struct sockaddr *) server, add_len))<0)
    {
        error("bind");
        printf("Error BIND: %s (%d)\n", strerror(errno), errno);
    }
}

void UDP_socket::connect(const char * argv)
{
    if ((gethostbyname(argv))<0)
    {
        error("connect");
        printf("Error connect: %s (%d)\n", strerror(errno), errno);
    }
    setServer(gethostbyname(argv));
}
